<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电话通信功能测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        h1 {
            text-align: center;
            color: #667eea;
            margin-bottom: 30px;
            font-size: 2.5rem;
        }
        
        .test-section {
            margin: 30px 0;
            padding: 20px;
            border: 2px solid #e1e8ed;
            border-radius: 10px;
            background: #f8f9fa;
        }
        
        .test-section h3 {
            color: #667eea;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .status {
            padding: 10px 15px;
            border-radius: 8px;
            margin: 10px 0;
            font-weight: bold;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .status.warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin: 5px;
            transition: all 0.3s ease;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .test-controls {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin: 15px 0;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 10px;
            margin: 5px 0;
            background: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .feature-status {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            color: white;
        }
        
        .feature-status.implemented {
            background: #28a745;
        }
        
        .feature-status.partial {
            background: #ffc107;
            color: #333;
        }
        
        .feature-status.planned {
            background: #6c757d;
        }
        
        .demo-link {
            text-align: center;
            margin: 30px 0;
        }
        
        .demo-link a {
            display: inline-block;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            text-decoration: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 18px;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        
        .demo-link a:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(40, 167, 69, 0.4);
        }
        
        .architecture-diagram {
            text-align: center;
            margin: 20px 0;
            font-family: monospace;
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            border: 1px solid #dee2e6;
        }
        
        .log-container {
            background: #1a1a1a;
            color: #00ff00;
            padding: 15px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            height: 200px;
            overflow-y: auto;
            margin: 10px 0;
        }
        
        .performance-metrics {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        
        .metric-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .metric-value {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
        }
        
        .metric-label {
            color: #6c757d;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📞 电话通信功能测试</h1>
        
        <!-- 功能概览 -->
        <div class="test-section">
            <h3>🎯 功能概览</h3>
            <p>这是一个基于WebSocket的实时语音通信系统，支持AI语音对话和电话通信功能。</p>
            
            <ul class="feature-list">
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>WebSocket实时通信</span>
                </li>
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>实时录音和音频传输</span>
                </li>
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>语音识别 (ASR)</span>
                </li>
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>AI对话 (LLM)</span>
                </li>
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>语音合成 (TTS)</span>
                </li>
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>实时通话状态管理</span>
                </li>
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>通话质量统计</span>
                </li>
                <li>
                    <div class="feature-status implemented">✓</div>
                    <span>错误处理和重连机制</span>
                </li>
                <li>
                    <div class="feature-status partial">~</div>
                    <span>多用户通话支持 (计划中)</span>
                </li>
                <li>
                    <div class="feature-status planned">○</div>
                    <span>通话录制功能 (计划中)</span>
                </li>
            </ul>
        </div>

        <!-- 系统架构 -->
        <div class="test-section">
            <h3>🏗️ 系统架构</h3>
            <div class="architecture-diagram">
                <pre>
┌─────────────────┐    WebSocket     ┌─────────────────┐
│   前端 Vue 3    │ ◄─────────────► │  Spring Boot    │
│                 │                 │   后端服务       │
│ • 实时录音       │                 │                 │
│ • 音频播放       │                 │ • WebSocket     │
│ • 通话状态管理    │                 │ • 会话管理       │
│ • UI交互        │                 │ • 异步处理       │
└─────────────────┘                 └─────────────────┘
                                              │
                               ┌──────────────┼──────────────┐
                               │              │              │
                    ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
                    │ ASR Service │  │ LLM Service │  │ TTS Service │
                    │ (阿里云)     │  │ (通义千问)   │  │ (阿里云)     │
                    └─────────────┘  └─────────────┘  └─────────────┘
                </pre>
            </div>
        </div>

        <!-- 测试控制 -->
        <div class="test-section">
            <h3>🧪 功能测试</h3>
            <div class="test-controls">
                <button onclick="testWebSocketConnection()">测试WebSocket连接</button>
                <button onclick="testMicrophoneAccess()">测试麦克风权限</button>
                <button onclick="testAudioPlayback()">测试音频播放</button>
                <button onclick="runPerformanceTest()">性能测试</button>
                <button onclick="clearTestLog()">清空日志</button>
            </div>
            
            <div id="testStatus" class="status info">
                📋 点击上方按钮开始测试各项功能
            </div>
            
            <div class="log-container" id="testLog">
                等待测试开始...
            </div>
        </div>

        <!-- 性能指标 -->
        <div class="test-section">
            <h3>📊 性能指标</h3>
            <div class="performance-metrics">
                <div class="metric-card">
                    <div class="metric-value" id="latencyMetric">0</div>
                    <div class="metric-label">平均延迟 (ms)</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value" id="throughputMetric">0</div>
                    <div class="metric-label">音频块/分钟</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value" id="errorRateMetric">0%</div>
                    <div class="metric-label">错误率</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value" id="connectionsMetric">0</div>
                    <div class="metric-label">活跃连接数</div>
                </div>
            </div>
        </div>

        <!-- 演示链接 -->
        <div class="demo-link">
            <a href="./frontend/voice-chat-frontend/index.html" target="_blank">
                🚀 打开语音聊天演示
            </a>
        </div>

        <!-- 技术说明 -->
        <div class="test-section">
            <h3>⚙️ 技术说明</h3>
            <h4>前端技术栈：</h4>
            <ul>
                <li><strong>Vue 3</strong> - 响应式前端框架</li>
                <li><strong>TypeScript</strong> - 类型安全</li>
                <li><strong>WebSocket API</strong> - 实时通信</li>
                <li><strong>MediaRecorder API</strong> - 音频录制</li>
                <li><strong>Web Audio API</strong> - 音频处理</li>
            </ul>

            <h4>后端技术栈：</h4>
            <ul>
                <li><strong>Spring Boot 3</strong> - 应用框架</li>
                <li><strong>WebSocket</strong> - 实时通信</li>
                <li><strong>阿里云ASR</strong> - 语音识别</li>
                <li><strong>通义千问</strong> - AI对话</li>
                <li><strong>阿里云TTS</strong> - 语音合成</li>
            </ul>

            <h4>核心特性：</h4>
            <ul>
                <li>🎤 <strong>实时录音</strong> - 1秒间隔的音频块传输</li>
                <li>🔄 <strong>异步处理</strong> - 非阻塞的音频处理流程</li>
                <li>📊 <strong>质量监控</strong> - 实时统计延迟、错误率等指标</li>
                <li>🛡️ <strong>错误恢复</strong> - 自动重连和错误处理</li>
                <li>🎯 <strong>优化传输</strong> - 音频压缩和大小限制</li>
            </ul>
        </div>
    </div>

    <script>
        let testLog = [];
        let performanceMetrics = {
            latency: [],
            throughput: 0,
            errors: 0,
            totalRequests: 0
        };

        function addTestLog(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${message}`;
            testLog.push(logEntry);
            
            const logContainer = document.getElementById('testLog');
            logContainer.innerHTML = testLog.slice(-20).join('\n');
            logContainer.scrollTop = logContainer.scrollHeight;
            
            console.log(logEntry);
        }

        function updateStatus(message, type = 'info') {
            const statusElement = document.getElementById('testStatus');
            statusElement.textContent = message;
            statusElement.className = `status ${type}`;
        }

        function updateMetrics() {
            const avgLatency = performanceMetrics.latency.length > 0 
                ? Math.round(performanceMetrics.latency.reduce((a, b) => a + b, 0) / performanceMetrics.latency.length)
                : 0;
            
            const errorRate = performanceMetrics.totalRequests > 0 
                ? Math.round((performanceMetrics.errors / performanceMetrics.totalRequests) * 100)
                : 0;

            document.getElementById('latencyMetric').textContent = avgLatency;
            document.getElementById('throughputMetric').textContent = performanceMetrics.throughput;
            document.getElementById('errorRateMetric').textContent = errorRate + '%';
            document.getElementById('connectionsMetric').textContent = '1'; // 简化显示
        }

        async function testWebSocketConnection() {
            updateStatus('🔄 正在测试WebSocket连接...', 'info');
            addTestLog('开始WebSocket连接测试');

            try {
                const ws = new WebSocket('ws://localhost:8123/api/ws/voice-chat');
                const startTime = Date.now();

                ws.onopen = function() {
                    const latency = Date.now() - startTime;
                    performanceMetrics.latency.push(latency);
                    performanceMetrics.totalRequests++;
                    
                    addTestLog(`✅ WebSocket连接成功，延迟: ${latency}ms`);
                    updateStatus('✅ WebSocket连接测试通过', 'success');
                    updateMetrics();
                    
                    // 发送测试消息
                    const testMessage = {
                        textInput: "测试连接",
                        sessionId: Date.now().toString()
                    };
                    ws.send(JSON.stringify(testMessage));
                    addTestLog('📤 发送测试消息');
                };

                ws.onmessage = function(event) {
                    addTestLog('📨 收到服务器响应: ' + event.data.substring(0, 100) + '...');
                };

                ws.onerror = function(error) {
                    performanceMetrics.errors++;
                    performanceMetrics.totalRequests++;
                    addTestLog('❌ WebSocket连接错误: ' + error);
                    updateStatus('❌ WebSocket连接测试失败', 'error');
                    updateMetrics();
                };

                ws.onclose = function(event) {
                    addTestLog(`🔌 WebSocket连接关闭: ${event.code} - ${event.reason}`);
                };

                // 5秒后关闭连接
                setTimeout(() => {
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.close();
                        addTestLog('⏰ 测试完成，关闭连接');
                    }
                }, 5000);

            } catch (error) {
                performanceMetrics.errors++;
                performanceMetrics.totalRequests++;
                addTestLog('❌ WebSocket连接异常: ' + error.message);
                updateStatus('❌ WebSocket连接测试失败', 'error');
                updateMetrics();
            }
        }

        async function testMicrophoneAccess() {
            updateStatus('🎤 正在测试麦克风权限...', 'info');
            addTestLog('开始麦克风权限测试');

            try {
                const stream = await navigator.mediaDevices.getUserMedia({ 
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        autoGainControl: true,
                        sampleRate: 24000
                    }
                });

                addTestLog('✅ 麦克风权限获取成功');
                addTestLog(`🎵 音频轨道数: ${stream.getAudioTracks().length}`);
                
                const audioTrack = stream.getAudioTracks()[0];
                if (audioTrack) {
                    const settings = audioTrack.getSettings();
                    addTestLog(`📊 音频设置: ${JSON.stringify(settings)}`);
                }

                // 测试录音
                const mediaRecorder = new MediaRecorder(stream);
                let recordedChunks = [];

                mediaRecorder.ondataavailable = function(event) {
                    if (event.data.size > 0) {
                        recordedChunks.push(event.data);
                        addTestLog(`📦 录制音频块: ${event.data.size} bytes`);
                    }
                };

                mediaRecorder.onstop = function() {
                    const totalSize = recordedChunks.reduce((sum, chunk) => sum + chunk.size, 0);
                    addTestLog(`🎯 录音测试完成，总大小: ${totalSize} bytes`);
                    updateStatus('✅ 麦克风测试通过', 'success');
                };

                mediaRecorder.start();
                addTestLog('🔴 开始录音测试...');

                // 3秒后停止录音
                setTimeout(() => {
                    mediaRecorder.stop();
                    stream.getTracks().forEach(track => track.stop());
                    addTestLog('⏹️ 停止录音测试');
                }, 3000);

            } catch (error) {
                performanceMetrics.errors++;
                addTestLog('❌ 麦克风权限测试失败: ' + error.message);
                updateStatus('❌ 麦克风测试失败', 'error');
                updateMetrics();
            }
        }

        async function testAudioPlayback() {
            updateStatus('🔊 正在测试音频播放...', 'info');
            addTestLog('开始音频播放测试');

            try {
                // 创建一个简单的测试音频
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = audioContext.createOscillator();
                const gainNode = audioContext.createGain();

                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);

                oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4音符
                gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);

                oscillator.start();
                addTestLog('🎵 播放测试音频 (440Hz)');

                setTimeout(() => {
                    oscillator.stop();
                    addTestLog('⏹️ 停止测试音频');
                    updateStatus('✅ 音频播放测试通过', 'success');
                }, 1000);

            } catch (error) {
                performanceMetrics.errors++;
                addTestLog('❌ 音频播放测试失败: ' + error.message);
                updateStatus('❌ 音频播放测试失败', 'error');
                updateMetrics();
            }
        }

        async function runPerformanceTest() {
            updateStatus('⚡ 正在运行性能测试...', 'info');
            addTestLog('开始性能测试');

            // 重置指标
            performanceMetrics = {
                latency: [],
                throughput: 0,
                errors: 0,
                totalRequests: 0
            };

            try {
                // 并发连接测试
                const connectionPromises = [];
                const testCount = 5;

                for (let i = 0; i < testCount; i++) {
                    connectionPromises.push(performSingleConnectionTest(i));
                }

                await Promise.all(connectionPromises);

                addTestLog(`📊 性能测试完成: ${testCount}个并发连接`);
                addTestLog(`📈 平均延迟: ${Math.round(performanceMetrics.latency.reduce((a, b) => a + b, 0) / performanceMetrics.latency.length)}ms`);
                addTestLog(`❌ 错误数: ${performanceMetrics.errors}/${performanceMetrics.totalRequests}`);
                
                updateStatus('✅ 性能测试完成', 'success');
                updateMetrics();

            } catch (error) {
                addTestLog('❌ 性能测试失败: ' + error.message);
                updateStatus('❌ 性能测试失败', 'error');
            }
        }

        async function performSingleConnectionTest(index) {
            return new Promise((resolve, reject) => {
                const ws = new WebSocket('ws://localhost:8123/api/ws/voice-chat');
                const startTime = Date.now();

                ws.onopen = function() {
                    const latency = Date.now() - startTime;
                    performanceMetrics.latency.push(latency);
                    performanceMetrics.totalRequests++;
                    
                    addTestLog(`✅ 连接 ${index + 1} 建立成功，延迟: ${latency}ms`);
                    
                    // 发送测试消息
                    ws.send(JSON.stringify({
                        textInput: `性能测试消息 ${index + 1}`,
                        sessionId: `perf-test-${index}-${Date.now()}`
                    }));

                    // 1秒后关闭连接
                    setTimeout(() => {
                        ws.close();
                        resolve();
                    }, 1000);
                };

                ws.onerror = function(error) {
                    performanceMetrics.errors++;
                    performanceMetrics.totalRequests++;
                    addTestLog(`❌ 连接 ${index + 1} 失败`);
                    reject(error);
                };

                ws.onclose = function() {
                    addTestLog(`🔌 连接 ${index + 1} 已关闭`);
                };
            });
        }

        function clearTestLog() {
            testLog = [];
            document.getElementById('testLog').innerHTML = '日志已清空...';
            updateStatus('📋 测试日志已清空', 'info');
        }

        // 页面加载时的初始化
        window.onload = function() {
            addTestLog('📞 电话通信功能测试工具已启动');
            addTestLog('🎯 系统支持实时语音通信和AI对话');
            addTestLog('🔧 点击上方按钮开始测试各项功能');
            updateStatus('🚀 测试工具已就绪，可以开始测试', 'info');
        };
    </script>
</body>
</html>
